//
//  YMDrawLineView.m
//  YMDrawingBoard
//
//  Created by 刘家俊 on 2020/12/2.
//  Copyright © 2020 余默. All rights reserved.
//

#import "YMDrawLineView.h"
#import "YMBezierPath.h"

@interface YMDrawLineView ()

/** 当前绘制的路径 */
@property (nonatomic, strong) YMBezierPath *path;
/** 保存当前绘制的所有路径 */
@property (nonatomic, strong) NSMutableArray *pathArr;

@end

@implementation YMDrawLineView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.backgroundColor = [UIColor whiteColor];
}

- (void)setLines:(NSArray *)lines {
    _lines = lines;
    
    [self reloadLines];
}

- (void)reloadLines {
    if (!self.lines.count) {
        return;
    }
    
    for (NSInteger i = 0; i < self.lines.count; i++) {
        NSArray *arr = self.lines[i];
        NSDictionary *dict = arr[0];
        CGPoint curP = CGPointMake([dict[@"x"] doubleValue], [dict[@"y"] doubleValue]);
        
        //创建路径
        YMBezierPath *path = [YMBezierPath bezierPath];
        path.lineJoinStyle = kCGLineJoinRound;//线的样式
        path.lineCapStyle = kCGLineCapRound;//线头的样式
        path.lineColor = [UIColor blackColor];
        path.lineWidth = 1;
        
        //设置路径的起点
        [path moveToPoint:curP];
        
        for (NSInteger i = 1; i < arr.count - 1; i++) {
            NSDictionary *dict = arr[i];
            CGPoint curM = CGPointMake([dict[@"x"] doubleValue], [dict[@"y"] doubleValue]);
            //添加一根线到当前手指所在的点
            [path addLineToPoint:curM];
        }
        
        [path stroke];
        //保存路径
        [self.pathArr addObject:path];
    }
}

- (void)drawRect:(CGRect)rect {
    //绘制所有路径
    for (YMBezierPath *path in self.pathArr) {
        if ([path isKindOfClass:[UIImage class]]) {
            UIImage *image = (UIImage *)path;
            [image drawInRect:rect];
        } else {
            [path.lineColor set];
            [path stroke];
        }
    }
}

#pragma mark - 懒加载
- (NSMutableArray *)pathArr {
    if (!_pathArr) {
        _pathArr = [NSMutableArray new];
    }
    return _pathArr;
}


@end
